
let str = 'create-react-app';
String.prototype.myReplace = function(pattern,replacement){
    debugger
  let result = '';//最终要返回的字符串
  let match;//每次匹配的结果
  let lastIndex=0;//上一次成功的索引.就 上一次成功匹配的字符串结束索引的下一位
  while((match = pattern.exec(this))!==null){
    //create-react-app lastIndex=0,index=6 create
    result += this.slice(lastIndex,match.index);
    if(typeof replacement === 'function'){
        result+=replacement(...match);//R createReactA
    }else{
        //$2 $1  match=['zhang san','zhang','san'] //$2 $1 => san zhang
        const replaced = replacement.replace(/\$(\d+)/g,function(matched,group1){
            return match[parseInt(group1)]//match[2]刚好是第2个分组
        });
        result+=replaced;
    }
    lastIndex=pattern.lastIndex;//8
  }
  result += this.slice(lastIndex);//createReactApp
  return result;
}

/* const result = str.myReplace(/-([a-z])/g,function(matched,group1,index,input){
   return group1.toUpperCase();
}); */
const str2 = 'zhang san';
const result = str2.myReplace(/(\w+) (\w+)/g,"$2 $1");
console.log(result);// san zhang